import React, { useState } from 'react';
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import login from './login.module.less';
import { checklogin } from '@/api/account';
import { Button, message, Checkbox, Form, Input } from 'antd';
import { useNavigate } from 'react-router-dom';

const LoginComponent = () => {
    const navigate = useNavigate();

    const onFinish = async (values) => {
        console.log('Success:', values);
        const { account, password } = values;
        const data = {
            account,
            password
        };
        await handleLogin(data);
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    // 登录验证
    const handleLogin = async (logindata) => {
        const { msg, code, token,id } = await checklogin(logindata);
        console.log(msg);
        if (code === 0) {
            sessionStorage.setItem('token', token);
            sessionStorage.setItem('password', logindata.password);
            sessionStorage.setItem('userId', id);
            message.success(msg);
            navigate('/home');
        } else {
            message.error(msg);
        }
    };

    return (
        <>
            <div className={login.box}>
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="账号"
                        name="account"
                        className={login.input}
                        rules={[{ required: true, message: '请输入账号' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                        className={login.passinp}
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button style={{ width: '400px' }} type="primary" htmlType="submit" className={login.loginbtn}>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </>
    );
};

export default LoginComponent;